package com.andy.module.progress

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okio.Buffer
import okio.ForwardingSource
import okio.Source
import java.io.IOException

/**
 * @creator:LuoFan
 * @date:2022/6/9
 * @description:
 */
class ProgressSource(source: Source, private val totalLength: Long, private val listener: ProgressListener?) : ForwardingSource(source) {

    var refreshTime = 200

    var currentLength = 0L

    var lastUpdateTime = 0L

    override fun read(sink: Buffer, byteCount: Long): Long {
        var readByte = 0L
        try {
            readByte = super.read(sink, byteCount)
            currentLength += readByte
            if (System.currentTimeMillis() - lastUpdateTime > refreshTime) {
                lastUpdateTime = System.currentTimeMillis()
                GlobalScope.launch(Dispatchers.Main) {
                    listener?.onChanged(currentLength, totalLength, currentLength * 100 / totalLength.toDouble())
                }
            }

        } catch (error: IOException) {
            throw error
        }
        return readByte
    }
}